package database;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.w3c.dom.Node;

public class Reading {
	
	private static String fileName;
	ArrayList<Fragment> fgtList;
	Document document;
	 Element root;
	
	public Reading(String _fileName){
		fileName=_fileName;
		 fgtList=new ArrayList<Fragment>();
	}
	
	public void parseFile(){
		fgtList=new ArrayList<Fragment>();
		 SAXBuilder builder = new SAXBuilder();
		 
		try {
			document = builder.build(fileName);
			root = document.getRootElement();
			List row = root.getChildren("fragment");
			//fragments
			for (int i = 0; i < row.size(); i++) {
				  Element fragment = (Element) row.get(i);
				  String fgtName = fragment.getAttribute("name").getValue();
				  String fgtProcess = fragment.getAttribute("process").getValue();
				  String fgtPosition = fragment.getAttribute("position").getValue();  
				 // System.out.println("Fragment Name : " + fgtName+" \t process : " + fgtProcess+" \t position : " + fgtPosition);
				  Fragment fgtTemp=new Fragment(fgtName, fgtProcess, fgtPosition);
				  
				  //mmm elements
				  List mmmes = fragment.getChildren("mmmElement");
				  for (int j = 0; j < mmmes.size(); j++) {
					 Element elt = (Element) mmmes.get(j);
					 String eltName = elt.getAttribute("name").getValue();
					 
					 //System.out.println("\t element = " + eltName);
					  List operations = elt.getChildren("operation");
					  ArrayList<Operation> ops=new ArrayList<Operation>();
					  for (int k = 0; k < operations.size(); k++) {
						  Element op = (Element) operations.get(k);
						  String opName = op.getAttribute("op").getValue();
						 // System.out.println("\t \t op = " + opName);
						  ops.add(getOperation(opName));
					  }
					  fgtTemp.addElement(eltName, ops);
				  }
				  
				//mmm relationships
				  List relationships = fragment.getChildren("mmmRelationship");
				  for (int j = 0; j < relationships.size(); j++) {
					 Element elt = (Element) relationships.get(j);
					 String relName = elt.getAttribute("name").getValue();
					 
					// System.out.println("\t relationship = " + relName);
					  List operations = elt.getChildren("operation");
					  ArrayList<Operation> ops=new ArrayList<Operation>();
					  for (int k = 0; k < operations.size(); k++) {
						  Element op = (Element) operations.get(k);
							 String opName = op.getAttribute("op").getValue();
							 //System.out.println("\t \t op = " + opName);
							 ops.add(getOperation(opName));
					  }
					  fgtTemp.addRelationship(relName, ops);
				  }
				  fgtList.add(fgtTemp);
			}
			//end parsing
			
		} catch (JDOMException e) {
			JOptionPane.showMessageDialog(null,e.getMessage(),
                    "File error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
		} catch (IOException e) {
			createXml();
			System.out.println("BD file create");
			parseFile();
//			JOptionPane.showMessageDialog(null, "BD file not found",
//                    "File error", JOptionPane.ERROR_MESSAGE);
//            System.exit(1);
		}
	 
	}
	
	 private Operation getOperation(String opName) {
		 if(opName.equals(Operation.D.toString()))
			 return Operation.D;
		 if(opName.equals(Operation.Q.toString()))
			 return Operation.Q;
		 if(opName.equals(Operation.R.toString()))
			 return Operation.R;
		 if(opName.equals(Operation.QR.toString()))
			 return Operation.QR;
		 if(opName.equals(Operation.RF.toString()))
			 return Operation.RF;
		 if(opName.equals(Operation.RFR.toString()))
			 return Operation.RFR;
		 if(opName.equals(Operation.NO.toString()))
			 return Operation.NO;
		return null;
	}
	 
	 public ArrayList<Fragment> getDB(){
		 return this.fgtList;
	 }

	 public void createXml() {
		 
		 Element racine = new Element("dataBase");
		 org.jdom.Document document = new Document(racine);
		 
		 try {
			 XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
			out.output(document, new FileOutputStream(fileName));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 
	    }
	 
//	public static void main(String[] args) throws Exception {
//		 String file="fragment.xml";
//		 Reading rf=new Reading(file);
//		 Writing wf=new Writing(file);
//		 rf.parseFile();
//		 DataBase db=new DataBase();
//		 db=rf.getDB();
//		 System.out.println(rf.db.toString());
//		 wf.writeNewFragment(db.getFragments().get(0));
//		 rf.parseFile();
//		 System.out.println(rf.db.toString());
//	 }
}